#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=200000+5;
const int M=1000000+5;
int n,t;
int a[N];
int nxt[N];
int last[M];
vector<int> g[N];
int main(){
    freopen("color.in","r",stdin);
    freopen("color.out","w",stdout);
    cin>>t;
    while(t--){
        cin>>n;
        memset(last,0,sizeof(last));
        for(int i=1;i<=n;i++){
            cin>>a[i];
            g[i].clear();
            nxt[i]=last[a[i]];
            int j=nxt[i];
            while(j){
                g[j].push_back(i);
                j=nxt[j];
            }
            last[a[i]]=i;
        }
        int l=-1,r=-1;
        int sum=0,ans=0;
        for(int i=1;i<=n+1;i++){
            if(i>r){
                l=-1,r=-1;
                ans+=sum;
                sum=0;
            }
            for(auto v:g[i]){
                if(i==r-1||l==-1){
                    l=i,r=v;
                    ans+=sum;
                    sum=a[v];
                }else{
                    if(a[v]>a[l]){
                        l=i,r=v;
                        sum=a[v];
                    }
                }
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
